//
//  Stack.c
//  栈的实现（2）
//
//  Created by 仲7 on 2025/1/30.
//
#include "Stack.h"
//栈的初始化
void STInit(ST* ps)
{
    ps->arr = NULL;
    ps->top = ps->capacity = 0;
}
//栈的销毁
void STDestroy(ST* ps)
{
    assert(ps);
    free(ps->arr);
    ps->arr = NULL;
    ps->top = ps->capacity = 0;
}
//栈判空
bool StackEmpty(ST* ps)
{
    assert(ps);
    return ps->top == 0;
}
//栈的增容
void STCapacityCheck(ST* ps)
{
    //栈满时，才会增容
    if(ps->top == ps->capacity)
    {
        ps->capacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
        STDataType* tmp = (STDataType*)malloc(ps->capacity * sizeof(STDataType));
        if(tmp == NULL)//判断增容的动态空间是否成功
        {
            perror("malloc fail");
            STDestroy(ps);
            exit(1);
        }
        ps->arr = tmp;
        
    }
}
//入栈
void STPush(ST* ps,STDataType x)
{
    assert(ps);
    //检查动态空间（是否栈满）
    STCapacityCheck(ps);
    //入栈（顺序表的尾插）
    ps->arr[ps->top++] = x;
}
//出栈
void STPop(ST* ps)
{
    assert(ps);
    //判空
    if(StackEmpty(ps))
    {
        fprintf(stderr,"Error: Stack underflow\n");
        return;
    }
    --ps->top;
}
//取栈顶元素
STDataType STTop(ST* ps)
{
    assert(ps);
//判空
// if(StackEmpty(ps))
//{
//        fprintf(stderr,"Error: Stack underflow\n");
//        return false;
//    }
//粗暴做法
    assert(!StackEmpty(ps));
    return ps->arr[ps->top-1];
}
